<?php
# vim: syntax=php tabstop=4 softtabstop=0 noexpandtab laststatus=1 ruler

/**
 * html/includes/api_folders.php
 *
 * Folders related functions for REST APIs.
 *
 * @author Andrea Dainese <andrea.dainese@gmail.com>
 * @copyright 2014-2016 Andrea Dainese
 * @license BSD-3-Clause https://github.com/dainok/unetlab/blob/master/LICENSE
 * @link http://www.unetlab.com/
 * @version 20160719
 */

/*
 * Function to add a folder to a path.
 *
 * @param   string     $name            Folder name
 * @param   string     $path            Path
 * @return  Array                       Return code (JSend data)
 */
//$BASE_LAB_USER=BASE_LAB.$username;
function apiAddFolder($db,$username,$name, $path,$role) {
	$rc = checkFolder(BASE_LAB.$path);
	if ($rc === 2) {
		// Folder is not valid
		$output['code'] = 400;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60009];
		return $output;
	} else if ($rc === 1) {
		// Folder does not exist
		$output['code'] = 404;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60008];
		return $output;
	}

	if ($path == '/') {
		//Non-administrator users cannot create folders in the '/' path
		if ($role != 'admin') {
			$output['code'] = 400;
			$output['status'] = 'fail';
			$output['message'] = $GLOBALS['messages'][60015];
			return $output;
		}
		// Avoid double '/'
		$path = '';
	}
	
	// Check if exists
	//$name1 = iconv('utf-8', 'gbk', $name);
	if (is_dir(BASE_LAB.$path.'/'.$name)) {
		// Folder already exists
		$output['code'] = 200;
		$output['status'] = 'success';
		$output['message'] = $GLOBALS['messages'][60014];
	} else {
		try {
			mkdir(BASE_LAB.$path.'/'.$name);
			//mkdir(BASE_LAB.$path.'/'.$name);
			$output['code'] = 200;
			$output['status'] = 'success';
			$output['message'] = $GLOBALS['messages'][60014];
		} catch (Exception $e) {
			error_log(date('M d H:i:s ').'ERROR: '.$GLOBALS['messages'][60015]);
			error_log(date('M d H:i:s ').(string) $e);
			$output['code'] = 400;
			$output['status'] = 'fail';
			$output['message'] = $GLOBALS['messages'][60015];
			return $output;
		}
		
		$fpath=$path.'/'.$name;
		$query = "insert into folder values(:fpath,:ppath,:name,'1',:username,:role);";
		try{
			$statement = $db -> prepare($query);
			$statement -> bindParam(':fpath', $fpath, PDO::PARAM_STR);
			$statement -> bindParam(':ppath', $path, PDO::PARAM_STR);
			$statement -> bindParam(':name', $name, PDO::PARAM_STR);
			$statement -> bindParam(':username', $username, PDO::PARAM_STR);
			$statement -> bindParam(':role', $role, PDO::PARAM_STR);
			$statement -> execute();
		}
		catch(Exception $e){
			$output['code'] = 400;
			$output['status'] = 'fail';
			$output['message'] = $GLOBALS['messages'][60067];
		}
	}

	return $output;
}

/**
 * Function to delete a folder.
 *
 * @param   string     $path            Path
 * @return  Array                       Return code (JSend data)
 */
function apiDeleteFolder($db,$path,$username) {
	$rc = checkFolder(BASE_LAB.$path);
	// 0有效且存在，1有效且不存在，2无效
	if ($rc === 2) {
		// Folder is not valid
		$output['code'] = 400;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60009];
		return $output;
	} else if ($rc === 1) {
		// Folder does not exist
		$output['code'] = 404;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60008];
		return $output;
	}

	if ($path == '/') {
		// Cannot delete '/'
		$output['code'] = 400;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60010];
		return $output;
	}
	try{
		$query = "delete from folder where f_path like '".$path.'%'."' and creator='".$username."';";
		$statement = $db -> prepare($query);
		$statement -> execute();
	}
	catch(Exception $e){
		$output['code'] = 400;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60068];
	}
	//$path1 = iconv('utf-8', 'gbk', $path);
	// 删除文件夹中实验室的所有tmp文件
	$cmd = 'find '.BASE_LAB.$path.' -name "*.unl" -exec sudo /opt/unetlab/wrappers/unl_wrapper -a delete -F "{}" -T 0 \;';  // Tenant not required for delete operation
	exec($cmd, $o, $rc);

	// Deleting the folder
	//iconv('utf-8', 'gbk', BASE_LAB.$path)
	$cmd = 'rm -rf "'.BASE_LAB.$path.'" 2>&1';
	exec($cmd, $o, $rc);
	if ($rc == 0) {
		$output['code'] = 200;
		$output['status'] = 'success';
		$output['message'] = 'Folder deleted';
		$output['message'] = $GLOBALS['messages'][60012];
	} else {
		$output['code'] = 400;
		$output['status'] = 'fail';
		$output['message'] = 'Cannot delete folder';
		$output['message'] = $GLOBALS['messages'][60011];
	}
	
	return $output;
}

/**
 * Function to edit a folder.
 *
 * @param   string     $s	            Full path of the source folder
 * @param   string     $d				Full path of the destination folder
 * @return  Array                       Return code (JSend data)
 */
function apiEditFolder($db, $s, $d,$username) {
	$rc = checkFolder(BASE_LAB.$s);
	if ($rc === 2) {
		// Folder is not valid
		$output['code'] = 400;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60009];
		return $output;
	} else if ($rc === 1) {
		// Folder does not exist
		$output['code'] = 404;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60008];
		return $output;
	}

	$rc = checkFolder(BASE_LAB.$d);
	if ($rc === 2) {
		// Folder is not valid
		$output['code'] = 401;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60047];
		return $output;
	} else if ($rc === 0) {
		// 已经有了
		$output['code'] = 402;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60046];
		return $output;
	}

	try{
	//数据库修改数据
	$d1=str_replace('//','/',$d);
	$pos1=strrpos($s,"/");
	$pos2=strrpos($d1,"/");

		$query = "update folder set f_path=replace(f_path,'".$s."','".$d1."'),p_path=replace(p_path,'".$s."','".$d1."') where f_path like '".$s.'/'.'%'."';";
		$statement = $db -> prepare($query);
		$statement -> execute();
		$d_move=substr($d1,0,$pos2);
		$d_rename=substr($d1,$pos2+1);
		$query = "update folder set f_path='".$d1."',p_path='".$d_move."',dir_name='".$d_rename."' where f_path='".$s."';";
		$statement = $db -> prepare($query);
		$statement -> execute();
	}
	catch(Exception $e){
		$output['code'] = 403;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60069];
	}

	// Moving the folder、rename
	//$ss1 = iconv('utf-8', 'gbk', $s);
	//$dd1 = iconv('utf-8', 'gbk', $d);
	$cmd = 'mv "'.BASE_LAB.$s.'" "'.BASE_LAB.$d.'" 2>&1';
	exec($cmd, $o, $rc);
	if ($rc == 0) {
		$output['code'] = 200;
		$output['status'] = 'success';
		$output['message'] = $GLOBALS['messages'][60049];
	} else {
		$output['code'] = 404;
		$output['status'] = 'fail';
		$output['message'] = 'Cannot move folder';
		$output['message'] = $GLOBALS['messages'][60048];
	}
	return $output;
}

/**
 * Function to get all folders from a path.
 *
 * @param   string     $path            Path
 * @return  Array                       List of folders (JSend data)
 */
function Getdbs2($db,$dbname,$sel, $where) {
	$data = Array();
	$query = 'SELECT '.$sel.' FROM '.$dbname.' WHERE '.$where.';';
	try {
		$statement = $db -> prepare($query);		
		$statement -> execute();
		//$idv=0;
		while ($row = $statement -> fetch(PDO::FETCH_ASSOC)) {			
			$data[$row[$sel]] = $row[$sel];	
		}
		
	} catch (Exception $e) {
		
	}
	return $data;
}
function apiGetFolders($path,$user,$db) {
	
	$rc = checkFolder(BASE_LAB.$path);
	if ($rc === 2) {
		// Folder is not valid
		$output['code'] = 400;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60009];
		return $output;
	} else if ($rc === 1) {
		// Folder does not exist
		$output['code'] = 404;
		$output['status'] = 'fail';
		$output['message'] = $GLOBALS['messages'][60008];
		return $output;
	}

	// Listing content
	$folders = Array();
	$labs = Array();
    //$path1=iconv('utf-8', 'gbk', $path);
	if ($path != '/') {
		// Adding '..' folder
		$folders[] = Array(
			'name' => '..',
			'path' => dirname($path)
		);
	}

	// Scanning directory
	//admin can view all files
	if($user['role'] == 'admin') {
		foreach (scandir(BASE_LAB.$path) as $element) {
			//$element1 = iconv('gbk', 'utf-8', $element);
			if (!in_array($element, array('.', '..'))) {
				if (is_dir(BASE_LAB.$path.'/'.$element)) {
					
					if ($path == '/') {
						$folders[] = Array(
							'name' => $element,
							'path' => '/'.$element
						);
					} else {
						$folders[] = Array(
							'name' => $element,
							'path' => $path.'/'.$element
						);
					}
					continue;
				}
				if (is_file(BASE_LAB.$path.'/'.$element) && preg_match('/^.+\.unl$/', $element)) {
					$yf_fname = str_replace('.unl', '', $element);
					if ($path == '/') {
						$labs[] = Array(
							'yf_name' => $yf_fname,
							'file' => $element,
							'path' => '/'.$element,
							'umtime' => filemtime(BASE_LAB.$path.'/'.$element),
							'mtime' => date ("Y-m-d H:i", filemtime(BASE_LAB.$path.'/'.$element))
						);
					} else {
						$labs[] = Array(
							'yf_name' => $yf_fname,
							'file' => $element,
							'path' => $path.'/'.$element,
							'umtime' => filemtime(BASE_LAB.$path.'/'.$element),
							'mtime' => date ("Y-m-d  H:i", filemtime(BASE_LAB.$path.'/'.$element))
						);
					}
					continue;
				}
			}
		}
	}
	else {  
		    $selfold=array($user['username']);
			//徐立新 
			if($user['role'] == 'teacher')
			{
				array_push($selfold,"public");
				if($user['classteacher'] != "")
				{
					$elements = explode(',', $user['classteacher']);
					foreach ($elements as $element) {
						if($element!="")
						{
						array_push($selfold,$element);	
							$stun=Getdbs2($db,"classstudent","username", "classname = '".$element."'");							
							foreach ($stun as $key => $value) {
								array_push($selfold,$value);
							}
						}			
							}
				}
			}
			else if($user['role'] == 'student')
			{
				array_push($selfold,"public");
				if($user['classstudent'] != "")
				{
					$elements = explode(',', $user['classstudent']);
					foreach ($elements as $element) {
						if($element!="")
						array_push($selfold,$element);		
						}
				}
				//array_push($selfold,$user['classstudent']);
			}
			else if($user['role'] == 'referee')
			{
				array_push($selfold,"public");
				if($user['matchreferee'] != "")
				{
					$elements = explode(',', $user['matchreferee']);
					foreach ($elements as $element) {
						if($element!="")
						{
						array_push($selfold,$element);	
							$splay=Getdbs2($db,"matchplayer","username", "matchname = '".$element."'");
							foreach ($splay as $key => $value) {
								array_push($selfold,$value);
							}
						}					
				}			
			}
			}
			else if($user['role'] == 'player')
			{
				if($user['matchplayer'] != "")
				{
					$elements = explode(',', $user['matchplayer']);
					foreach ($elements as $element) {
						if($element!="")
						array_push($selfold,$element);		
						}
				}
				
			}
			else if($user['role'] == 'user')
			{
				array_push($selfold,"public");
			}
			$selfold=array_unique($selfold);//去重复
			foreach (scandir(BASE_LAB.$path) as $element) {
				//$element1 = iconv('gbk', 'utf-8', $element);
				if (!in_array($element, array('.', '..'))) {
					if (is_dir(BASE_LAB.$path.'/'.$element)) {
						if ($path == '/') {
							if (in_array($element,$selfold)) {
								$folders[] = Array(
									'name' => $element,
									'path' => '/'.$element
								);
							}
						} else {
							$tt=explode('/', $path)[1];
							if (in_array($tt,$selfold) ) {
								$folders[] = Array(
									'name' => $element,
									'path' => $path.'/'.$element
								);
							}
						}
						continue;
					}
					if (is_file(BASE_LAB.$path.'/'.$element) && preg_match('/^.+\.unl$/', $element)) {
						$yf_fname = str_replace('.unl', '', $element);
						if ($path == '/') {
							if ($element == $user['username']) {
								$labs[] = Array(
									'yf_name' => $yf_fname,
									'file' => $element,
									'path' => '/'.$element,
									'umtime' => filemtime(BASE_LAB.$path.'/'.$element),
									'mtime' => date ("Y-m-d H:i", filemtime(BASE_LAB.$path.'/'.$element))
								);
							}
						} else {
							$tt=explode('/', $path)[1];
							if (in_array($tt,$selfold) ) {
								$labs[] = Array(
									'yf_name' => $yf_fname,
									'file' => $element,
									'path' => $path.'/'.$element,
									'umtime' => filemtime(BASE_LAB.$path.'/'.$element),
									'mtime' => date ("Y-m-d  H:i", filemtime(BASE_LAB.$path.'/'.$element))
								);
							}
						}
						continue;
					}
				}
			}
			
		}



	// Sorting
	usort($folders, function($a, $b){
		return strnatcasecmp($a['name'], $b['name']);
	});
	usort($labs, function($a, $b){
		return strnatcasecmp($a['file'], $b['file']);
	});
	//Put the public folder at the top
	$flag = 0;
	for ($i = 0; $i < count($folders, COUNT_NORMAL); $i++) {
		if ($folders[$i]['name'] == 'public') {
			$flag = 1;
			break;
		}
	}
	if ($flag) {
		$temp = $folders[$i];
		for ($j = $i; $j > 0; $j--) {
			$folders[$j] = $folders[$j - 1];
		}
		$folders[0] = $temp;
	}

	// Printing info
	$output['code'] = 200;
	$output['status'] = 'success';
	// $output['message'] = $GLOBALS['messages'][60007];
	$output['message'] = $path;
	$output['data'] = Array(
		'folders' => $folders,
		'labs' => $labs
	);
	return $output;
}
?>
